﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Reflection;

using HIHS.BaseLib;
using HIHS.BaseLib.Basics;
using HIHS.Tool;
using HIHS.Logic.User;

namespace HIHS.Form.Main
{

    /// <summary>
    /// 菜单设置  
    /// </summary>
    public partial class FunctionControl : BaseShowControl //继承BaseShowControl 弹出窗体显示
    {
        TreeNode currentNode;
        private List<FunctionEntity> AppFunTree;
        private List<FunctionEntity> AppFunMunes;
        public FunctionControl()
        {
            InitializeComponent();
        }
        private void FunctionControl_Load(object sender, EventArgs e)
        {
            this.Window.Text = "设置";
            List<dynamic> list = new List<dynamic>();
            string[] names = typeof(FunctionType).GetEnumNames();
            foreach (var item in names)
                list.Add(new { Key = item, Value = Enum.Parse(typeof(FunctionType), item) });
            this.comboBoxFunctionType.DataSource = list;
            this.comboBoxFunctionType.DisplayMember = "Key";
            this.comboBoxFunctionType.ValueMember = "Value";
            this.comboBoxFunctionType.SelectedIndex = 0;
            this.comboBoxFunctionType.SelectedValueChanged += comboBoxFunctionType_SelectedValueChanged;
            this.comboBoxItemType.SelectedIndexChanged += comboBoxItemType_SelectedIndexChanged;
        }

        void comboBoxItemType_SelectedIndexChanged(object sender, EventArgs e)
        {
            string itemtype = (string)comboBoxItemType.SelectedItem;
            if (itemtype == "Group")
            {
                checkEditIndex.Enabled = false;
                checkEditLoadStart.Enabled = false;
                groupControlClass.Enabled = false;
                comboBoxFunctionType.Enabled = false;
            }
            else
            {
                comboBoxFunctionType.Enabled = false;
                checkEditIndex.Enabled = true;
                checkEditLoadStart.Enabled = true;
                groupControlClass.Enabled = true;
            }
        }

        public override void ReloadData(object data)
        {
            treeView1.Nodes.Clear();
            AppFunTree = HIHSApplication.AppFunTree.Where(o=>o.Id>0).ToList();
            AppFunMunes = HIHSApplication.AppFunMunes;
            foreach (var item in AppFunTree)
            {
                FillTree(this.treeView1.Nodes, item);
            }
            if(AppFunTree!=null)
                treeView1_NodeMouseClick(this.treeView1, new TreeNodeMouseClickEventArgs(treeView1.TopNode, MouseButtons.Left, 1, 0, 0));
        }

        private void FillTree(TreeNodeCollection nodes, FunctionEntity fe)
        {
            if (fe != null)
            {
                TreeNode tn = new TreeNode();
                tn.Text = fe.Title.Language();
                tn.Tag = fe;
                if (fe.Items != null)
                    foreach (var item in fe.Items)
                        FillTree(tn.Nodes, item);
                nodes.Add(tn);
            }
        }

        public override void LanguageBinding()
        {

        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            TreeNode tn = e.Node;
            if (tn == null || tn == currentNode)
                return;
            currentNode = tn;
            FunctionEntity fe = tn.Tag as FunctionEntity;
            textBoxKeyCode.Text = fe.AppCode;
            textBoxParent.Text = fe.Parent;
            textBoxTitle.Text = fe.Title;
            textBoxRemarks.Text = fe.Remarks;
            textBoxHotKey.Text = fe.HotKey.ToString();
            this.checkEditIndex.Checked = fe.Index;
            this.checkEditIsCreate.Checked = fe.IsCreate;
            this.checkEditLoadStart.Checked = fe.StartLoad;
            this.checkEditEnabled.Checked = fe.Enabled;

            if (fe.ClassInfo != null)
            {
                if (FillComboBoxClass(AppDomain.CurrentDomain.BaseDirectory + fe.ClassInfo.DLLName))
                {
                    buttonEditDLL.Text = fe.ClassInfo.DLLName;
                    ComboBoxClass.SelectedValue = fe.ClassInfo.ClassFillName;
                }
            }
            else
            {
                buttonEditDLL.Text = "";
                ComboBoxClass.SelectedItem = null;
            }

            this.textBoxTip.Text = fe.Tip != null ? fe.Tip.Text : "";
            comboBoxFunctionType.SelectedValue = fe.FunctionType;
            comboBoxItemType.SelectedItem = fe.ItemType == FunctionItemType.Group ? "Group" : "Item";
            if (fe.ItemParamter!=null)
               textBoxParam.Text = fe.ItemParamter.ToString();

        }

        private void buttonEditDLL_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "(*.dll)|*.dll";
            if (DialogResult.OK == of.ShowDialog())
                if (FillComboBoxClass(of.FileName))
                    buttonEditDLL.Text = of.SafeFileName;
        }

        private bool FillComboBoxClass(string FileName)
        {
            ComboBoxClass.DataSource = null;
            Type[] types = null;
            try
            {
                Assembly ass = Assembly.Load(System.Reflection.Assembly.LoadFile(FileName).GetName());
                types = ass.GetTypes();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return false;
            }
            FunctionType ft = (FunctionType)comboBoxFunctionType.SelectedValue;
            Type type = typeof(BaseFunctionControl);

            List<dynamic> list = new List<dynamic>();
            if (ft == FunctionType.Function)
            {
                type = typeof(ICustom);
                if (types.Any(t => type.IsAssignableFrom(t)))
                {
                    var ts = types.Where(t => type.IsAssignableFrom(t));
                    foreach (var item in ts)
                        list.Add(new { Key = item.FullName, Value = item.FullName });
                }
            }
            else
            {
                if (types.Any(t => t.IsSubclassOf(type)))
                {
                    var ts = types.Where(t => t.IsSubclassOf(type));
                    Type ct = typeof(BaseFunctionControl);
                    Type st = typeof(BaseShowControl);
                    Type wt = typeof(WebBrowserControl);
                    foreach (var item in ts)
                    {
                        string name = "Control";
                        if (item.IsSubclassOf(wt))
                            name = "Web";
                        else if (item.IsSubclassOf(st))
                            name = "Window";
                        list.Add(new { Key = string.Format("{0}({1})", item.FullName, name), Value = item.FullName });
                    }
                }
            }
            ComboBoxClass.DataSource = list;
            ComboBoxClass.DisplayMember = "Key";
            ComboBoxClass.ValueMember = "Value";

            return true;
        }

        private void comboBoxFunctionType_SelectedValueChanged(object sender, EventArgs e)
        {
            FunctionType ft = (FunctionType)comboBoxFunctionType.SelectedValue;
            groupControlImage.Enabled = true;
            groupControlClass.Enabled = true;
            comboBoxItemType.Enabled = true;
            switch (ft)
            {
                case FunctionType.Control:
                    checkEditIndex.Enabled = true;
                    break;
                case FunctionType.Function:
                    checkEditIndex.Enabled = false;
                    break;
                case FunctionType.Authorization:
                    comboBoxItemType.Enabled = false;
                    groupControlImage.Enabled = false;
                    groupControlClass.Enabled = false;
                    break;
            }
        }

        private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            删除ToolStripMenuItem.Enabled = false;
            添加ToolStripMenuItem.Enabled = true;
            if (e.Button == MouseButtons.Right)
            {
                Point ClickPoint = new Point(e.X, e.Y);
                TreeNode CurrentNode = treeView1.GetNodeAt(ClickPoint);
                if (CurrentNode != null)
                {
                    FunctionEntity fe = (FunctionEntity)CurrentNode.Tag;
                    if (string.IsNullOrEmpty(fe.AppCode))
                        添加ToolStripMenuItem.Enabled = false;

                    treeView1.SelectedNode = CurrentNode;//选中这个节点
                    treeView1_NodeMouseClick(this.treeView1, new TreeNodeMouseClickEventArgs(CurrentNode, MouseButtons.Left, 1, 0, 0));
                    删除ToolStripMenuItem.Enabled = true;
                }
                else
                    treeView1.SelectedNode = null;
            }
        }

        private void 添加ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode parentTn = this.treeView1.SelectedNode;
            FunctionEntity fe = new FunctionEntity();
            fe.Title = "新应用";
            fe.AppCode = Guid.NewGuid().ToString();
            TreeNode tn = new TreeNode { Text = fe.Title.Language(), Tag = fe };
            AppFunMunes.Add(fe);
            if (parentTn != null)
            {
                fe.Parent = ((FunctionEntity)parentTn.Tag).AppCode;
                parentTn.Nodes.Add(tn);
                FunctionEntity pfe = (FunctionEntity)parentTn.Tag;
                if (pfe.Items == null)
                    pfe.Items = new List<FunctionEntity>();
                pfe.Items.Add(fe);
            }
            else
            {
                AppFunTree.Add(fe);
                treeView1.Nodes.Add(tn);
            }

            treeView1.SelectedNode = tn;
            treeView1_NodeMouseClick(this.treeView1, new TreeNodeMouseClickEventArgs(tn, MouseButtons.Left, 1, 0, 0));
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode tn = this.treeView1.SelectedNode;
            FunctionEntity fe= (FunctionEntity)tn.Tag;
            AppFunMunes.Remove(fe);
            if (!string.IsNullOrEmpty(fe.Parent))
                AppFunMunes.First(o => o.AppCode == fe.Parent).Items.Remove(fe);

            if (tn.NextVisibleNode != null)
                treeView1.SelectedNode = tn.NextVisibleNode;
            else if (tn.Parent != null)
                treeView1.SelectedNode = tn.Parent;
            else
                treeView1.SelectedNode = null;
            if (tn != null)
                this.treeView1.Nodes.Remove(tn);
            treeView1_NodeMouseClick(this.treeView1, new TreeNodeMouseClickEventArgs(treeView1.SelectedNode, MouseButtons.Left, 1, 0, 0));
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            if (this.treeView1.SelectedNode == null)
                return;
            TreeNode tn = this.treeView1.SelectedNode;
            FunctionEntity currentfe = (FunctionEntity)tn.Tag;

            //FunctionEntity parentfe = null;

            if (string.IsNullOrEmpty(textBoxKeyCode.Text))
            {
                MessageBox.Show("编号必填".Language());
                return;
            }

            ////if (AppFunMunes.Any(o => !string.IsNullOrEmpty(o.KeyCode) && o.KeyCode == textBoxKeyCode.Text))
            ////{
            ////    MessageBox.Show("编号重复");
            ////    return;
            ////}
            //if (AppFunMunes.Any(o => !string.IsNullOrEmpty(o.KeyCode) && o.KeyCode == currentfe.Parent))
            //    parentfe = AppFunMunes.First(o => !string.IsNullOrEmpty(o.KeyCode) && o.KeyCode == currentfe.Parent);

            currentfe.KeyCode = textBoxKeyCode.Text;
            currentfe.Title = textBoxTitle.Text;

            currentfe.Remarks = textBoxRemarks.Text;
            //textBoxHotKey.Text = fe.HotKey.ToString();
            currentfe.Enabled = checkEditEnabled.Checked;
            currentfe.IsCreate = checkEditIsCreate.Checked;
            currentfe.FunctionType = (FunctionType)comboBoxFunctionType.SelectedValue;

            currentfe.ItemType = comboBoxItemType.SelectedItem.ToString() == "Group" ? FunctionItemType.Group : FunctionItemType.Item;

            currentfe.Index = checkEditIndex.Checked;
            currentfe.StartLoad = checkEditLoadStart.Checked;

            if (!string.IsNullOrEmpty(buttonEditDLL.Text) && ComboBoxClass.SelectedValue != null)
                currentfe.ClassInfo = new ClassInfo { DLLName = buttonEditDLL.Text, ClassFillName = ComboBoxClass.SelectedValue.ToString() };

            currentfe.Tip = new FunctionTip { Text = textBoxTip.Text, Title = "提示" };
            currentfe.ItemParamter = this.textBoxParam.Text;
            MessageBox.Show("保存成功".Language());
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            UserAppsLogic ual=new UserAppsLogic();
            //筛掉系统菜单然后上传保存
            if (ual.SaveFunctionEntity(AppFunMunes.Where(o => o.Id > 0).ToList()) > 0)
            { 
            
            }
        }
    }
}
